package auth

import config.JwtConfig
import play.api.http.HeaderNames
import play.api.mvc.RequestHeader
import shared.pojo.Role
import utils.JwtUtils

import java.time.Clock
import scala.concurrent.Future
import scala.util.Failure

/**
 * Created by yz on 10/8/2022
 */
object AuthTool {

  private implicit val clock: Clock = Clock.systemUTC

  def decodeAuthorizationHeader(header: String)(implicit config: JwtConfig) = {
    val tokenType = "Bearer"
    val headerParts = header.split(" ")
    Option(headerParts).filter(_.length == 2).filter(tokenType equalsIgnoreCase _.head).map(_.last).map { token =>
      JwtUtils.decodeToken(config, token)
    }.getOrElse(Failure(new RuntimeException("Unable to parse the authorization header as a Jwt token")))
  }

  def authenticate(request: RequestHeader)(implicit config: JwtConfig) = {
    Future.fromTry {
      request.headers.get("X-Authorization").orElse(request.headers.get(HeaderNames.AUTHORIZATION)).map { header =>
        decodeAuthorizationHeader(header)
      }.getOrElse(Failure(new RuntimeException("Authorization header not found")))
    }
  }

  def adminAuth(implicit authAction: AuthActionWrapper) = authAction(Role.Admin)

  def memberAuth(implicit authAction: AuthActionWrapper) = authAction(Role.Member)

  def companyMemberAuth(implicit authAction: AuthActionWrapper) = authAction(Role.CompanyMember)


}
